<template>
  <div class="paren">
    <div class="table-wrapper">
      <el-table 
        :data="filteredTableData"
        height="100%"
        :header-cell-style="{ color: 'rgb(82,85,96)' }"
      >
        <el-table-column prop="name" label="Name" show-overflow-tooltip></el-table-column>
        <el-table-column prop="auth" label="Auth" show-overflow-tooltip></el-table-column>
        <el-table-column prop="dealer" label="Dealer" show-overflow-tooltip></el-table-column>
        <el-table-column prop="account" label="Account" show-overflow-tooltip></el-table-column>
        <el-table-column label="Details" width="240px">
          <template #default="scope">
            <el-button @click="handleEdit(scope.$index)">Modify</el-button>
            <el-button type="danger" @click="handleDelete(scope.$index)">Delete</el-button>
          </template>
        </el-table-column>
      </el-table> 
    </div>

    

    <!-- 分页 -->
    <div class="pagination-footer">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        layout="total, prev, pager, next, jumper"
        :total="tableData.length"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
      
      <div class="add-button">
        <el-button type="primary" @click="handleAdd" v-if="auth === 10">Add</el-button>
      </div>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="30%" class="large-dialog">
      <el-form :model="formData" label-width="100px">
        <el-form-item label="Name" required>
          <el-input v-model="formData.name"></el-input>
        </el-form-item>
        <el-form-item label="Auth" required>
          <el-input 
            v-model="formData.auth"
            :disabled="isAuth"
            type="number"
            min="1"
            max="10"
            @change="validateAuth"
            @keydown.native="preventNonNumberInput"
          ></el-input>
        </el-form-item>
        <el-form-item label="Dealer" required>
          <el-input v-model="formData.dealer" :disabled="isAuth"></el-input>
        </el-form-item>
        <el-form-item label="Account" required>
          <el-input v-model="formData.account" :disabled="isEditing"></el-input>
        </el-form-item>
        <el-form-item label="Password" required>
          <el-input v-model="formData.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="Logo" required>
          <el-upload
            class="avatar-uploader"
            action="#" 
            :show-file-list="false"
            :auto-upload="false"
            :on-change="handleLogoChange"
          >
            <img v-if="logoPreview" :src="logoPreview" class="avatar">
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="handleConfirm">confirm</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
  import { ref,onMounted,computed } from 'vue';
  import axios from 'axios';
  import { ElMessage,ElMessageBox } from 'element-plus';
  import { Plus } from '@element-plus/icons-vue';
  import {compressImg} from '../../utils';
  import { useManageStore } from '../../store/manageStore';
  import { useLoading } from '../../utils/loading';
  const manageStore = useManageStore()
  const { showLoading, hideLoading } = useLoading();
  const BASE_URL = import.meta.env.VITE_API_URL

  const tableData = ref([]);
  const dialogVisible = ref(false);
  const dialogTitle = ref('添加数据');
  const isEditing = ref(false);
  const isAuth = ref(true);
  const editIndex = ref(-1);
  const logoFile = ref(null);//储存文件对象
  const logoPreview = ref('');//用于浏览的URL
  const dealer = computed(() => manageStore.dealer)
  const auth = computed(() => manageStore.auth)
  //分页变量
  const pagination = ref({
    currentPage:1,
    pageSize:20,
    total:0
  })

  const formData = ref({
    name: '',
    auth: '',
    dealer: dealer.value,
    account: '',
    password: '',
    logo: '',
    userId: '',
  });
  
  onMounted(() => {
    fetchData()
  })
  //auth过滤dealer方法
  const filteredTableData = computed(() => {
    if (auth.value >= 10) return tableData.value;
    return tableData.value.filter(item => item.dealer === dealer.value);
  });
  // 获取数据的函数
  const fetchData = () => {
    showLoading('Loading data...')

    axios.get(`${BASE_URL}manage/userList`,{
      params:{
        page:pagination.value.currentPage,
        size:pagination.value.pageSize,
      }
    })

    .then(res => {
      let resultData = res.data;
      if(resultData.code != 0){
        ElMessage.error(resultData.msg)
      }else{
        // 如果 auth < 10，只保留当前 dealer 的数据
        if (auth.value < 10) {
          tableData.value = resultData.data.filter(item => item.dealer === dealer.value);
        } else {
          tableData.value = resultData.data;
        }
      }
    })
    .catch(error => {
      ElMessage.error('Failed to obtain data')
    })
    .finally(() => {
      hideLoading()
    })
  }
  
  //分页页数
  const handleSizeChange = (val) => {
    pagination.value.pageSize = val
    fetchData()
  }
  const handleCurrentChange = (val) => {
    pagination.value.currentPage = val
    fetchData()
  }

  const handleAdd = () => {
  dialogTitle.value = 'Add data';
  isEditing.value = false;
  if(auth.value >= 10) {
    isAuth.value = false;
  }
  formData.value = {
    name: '',
    auth: '1',
    dealer: dealer.value,
    account: '',
    password: '',
    logo: '',
  };
  logoPreview.value = '';  // 清空logo预览
  dialogVisible.value = true;
};

const handleEdit = (index) => {
  dialogTitle.value = 'Modify data';
  isEditing.value = true;
  if(auth.value >= 10) {
    isAuth.value = false;
  }
  editIndex.value = index;
  // 深拷贝当前行数据到表单，避免直接引用
  formData.value = JSON.parse(JSON.stringify(tableData.value[index]));
   // 如果有logo，设置预览
  if (formData.value.logo) {
    logoPreview.value = formData.value.logo;
  }
  dialogVisible.value = true;
};
//删除方法
const handleDelete = async(index) => {
  try {
    await ElMessageBox.confirm(
      'Are you sure you want to delete this admin?',
      'Deletion confirmation',
      {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning',
        // 可以添加自定义类名
        customClass: 'delete-confirm-box',
      }
    )
    showLoading('Deleting...');
    const userToDelete = tableData.value[index];
     if (!userToDelete.userId) {
      ElMessage.error('User ID is missing');
      return;
    }
    await axios.delete(`${BASE_URL}manage/delUser`,{
      params: { userId:userToDelete.userId  }
    })
    tableData.value.splice(index, 1);
    ElMessage.success('Deletion successful');
  } catch(error) {
    if (error !== 'cancel') {
      ElMessage.error('Deletion failed:' + error.msg)
    }
  } finally {
    hideLoading();
  }
};

//处理logo文件选择
const handleLogoChange = async(file) => {
  try {
    showLoading('Uploading logo...');
    logoFile.value = file.raw; //储存原始文件对象
    logoPreview.value = URL.createObjectURL(file.raw);//创建预览RUL

    const formDataForUpload = new FormData();
    const compressedFile = await compressImg(logoFile.value);
    formDataForUpload.append('multipartFile', compressedFile);
    formDataForUpload.append('fileName', Date.now() + '.jpg');

    const response = await axios.post(`${BASE_URL}upload/file`, formDataForUpload, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });

    if (response.data.code === 0) {
      const url = response.data.data.url;
      formData.value.logo = url;
    } else {
      ElMessage.error(response.data.msg + 'The picture upload failed. Please try again.');
    }
  }catch(error) {
    ElMessage.error('The picture upload failed: ' + error.msg);
  } finally {
    hideLoading();
  }
}

//添加和修改数据方法
const handleConfirm = async() => {
  if(!formData.value.name){
    ElMessage.warning('Please enter your name')
    return
  }else if(!formData.value.account){
    ElMessage.warning('Please enter your account number')
    return
  }else if(!formData.value.password){
    ElMessage.warning('Please enter the password')
    return
  }else if(!formData.value.logo){
    ElMessage.warning('Please select an avatar')
    return
  }

  try {
    showLoading(isEditing.value ? 'Updating data...' : 'Adding data...');
    if (isEditing.value) {
      // 修改数据
      const response = await axios.post(`${BASE_URL}manage/updateUser`,formData.value); 
      // 检查响应是否成功
      if (response.data.code === 0) {
        // 使用服务器返回的更新后数据更新表格
        tableData.value[editIndex.value] = response.data.data;
        ElMessage.success('Data update was successful');
        dialogVisible.value = false;
      } else {
        ElMessage.error(response.data.msg);
      }

    } else {
        // 添加数据
        const response = await axios.post(`${BASE_URL}manage/addUser`, formData.value);
        tableData.value.push({ ...formData.value });
        ElMessage.success('Added successfully');
      }
      // 清理预览URL
      if (logoPreview.value) {
        URL.revokeObjectURL(logoPreview.value);
      }
      dialogVisible.value = false;
    }catch(error) {
      ElMessage.error('Operation failed: ' + error.msg);
    } finally {
      hideLoading();
    }
  };
  const preventNonNumberInput = (e) => {
    // 阻止输入非数字字符
    if (['e', 'E', '+', '-'].includes(e.key)) {
      e.preventDefault();
    }
  };
  const validateAuth = () => {
    if (formData.value.auth > 10) {
      formData.value.auth = 10;
      ElMessage.warning('The maximum permission value is 10');
    } else if (formData.value.auth < 1) {
      formData.value.auth = 1;
      ElMessage.warning('The minimum permission value is 1');
    }
  };
</script>

<style scoped>
  .paren {
    display: flex;
    flex-direction: column;
    height: calc(100vh - 180px);
    box-sizing: border-box;
    background-color: white;
    color: black;
  }
  .table-wrapper {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    margin-bottom: 10px;
  }
  /* 固定表头样式 */
  :deep(.el-table__header-wrapper) {
    position: sticky;
    top: 0;
    z-index: 10;
  }
  /* 表格滚动区域 */
  :deep(.el-table__body-wrapper) {
    overflow-y: auto;
    flex: 1;
  }
  /* 表格全局居中样式 */
  :deep(.el-table .el-table__cell) {
    text-align: center;
    height: 80px;
    font-size: 20px;
  }
  :deep(.el-table .el-table__cell .cell) {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    max-width: 240px;
  }
  :deep(.el-table .el-button) {
    font-size: 18px;
    width: 80px;
    height: 35px;
    border-radius: 8px;
    }
  
  /* 固定底部分页 */
  .pagination-footer {
    flex-shrink: 0;
    padding: 18px 50px 18px 100px;
    display: flex;
    justify-content: flex-end;
    color: rgb(79, 83, 79);
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); /* 标准阴影 */
  }
  :deep(.el-pagination),
  :deep(.el-pagination .number),
  :deep(.el-pagination .el-input__inner),
  :deep(.el-pagination__total),
  :deep(.el-pagination__sizes) {
    font-size: 20px;
  }
  .add-button {
    display: flex;
    justify-content: flex-end;
    margin-left: 30px;
  }
  :deep(.add-button .el-button){
    font-size: 20px;
    width: 80px;
    height: 40px;
    border-radius: 10px;
  }
  :deep(.large-dialog .el-form-item__label),
  :deep(.large-dialog .el-input__inner) {
    height: 40px !important;
    font-size: 18px !important;
    line-height: 40px !important;
  }
  /* 添加图片样式 */
  .avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
    background-color: transparent !;
  }
  :deep(.dialog-footer .el-button) {
    font-size: 18px;
    padding: 12px 24px;
    height: 38px;
    width: 80px;
    margin-left: 20px;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    background-color: transparent;
  }
  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }
  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }
  

</style>